﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Asteroids
{
    class Enemy : Ship
    {
        

        public Enemy(int mod, Vector2 pos, Vector2 vel) : base(mod, pos, vel) 
        {
            m_moveChance = Game1.shipModels[mod].moveChance;
        }

        public override void Update(GameTime gametime)
        {
            if (m_random.Next(100) < 1 + m_moveChance)
            {
                thrust += new Vector2(m_random.Next(-2 * m_moveChance, 2 * m_moveChance) / 4.0f, m_random.Next(-2 * m_moveChance, 2 * m_moveChance) / 4.0f);
            }

            base.Update(gametime);
        }

        public Bullet attackPlayer(Player player)
        {
            //b = self.velocity.X
            //c = self.velocity.Y
            //t = angle bullet must leave at
            //x = number of frames to collision

            //player.centerPosition.X = 2
            //player.centerPosition.Y = 3
            //player.velocity.X = 4
            //player.velocity.Y = 5
            //self.centerPosition.X = 6
            //self.centerPosition.Y = 7
            //max_velocity = 8


            //Solve for:
            //b = sin(t) * 8
            //c = cos(t) * 8
            //2 + x * 4 = 6 + x * b
            //3 + x * 5 = 7 + x * c

            //4x-4 = bx
            //5x-4 = cx

            //4-4/x = b
            //5-4/x = c

            //-1 = b-c

            //b = c - 1

            //c = 8sin(t) + 1 = 8cos(t)

            //t = arccos((8sin(t) + 1) / 8)

            //Well, that's how it should work anyway, but I'll do it simply so that I don't have to worry about it.
            float deltaX = player.centerPosition.X - centerPosition.X;
            float deltaY = player.centerPosition.Y - centerPosition.Y;
            Vector2 vel = normalizeVelocity(deltaX, deltaY);
            float angle = (float)Math.Atan2(deltaY, deltaX);
            Bullet rtnBullet = new Bullet(0, 8, centerPosition + new Vector2(radius * (float)Math.Cos(angle), radius * (float)Math.Sin(angle)), vel);
            rtnBullet.rotation = angle;
            return rtnBullet;
        }

        //Scales a large velocity to fit the max_velocity variable without truncating.
        private Vector2 normalizeVelocity(float x, float y)
        {
            float ratio1 = Math.Abs(x / m_maxSpeed);
            float ratio2 = Math.Abs(y / m_maxSpeed);
            float trueRatio = ratio1 > ratio2 ? ratio1 : ratio2;
            return new Vector2(x / trueRatio, y / trueRatio);
        }
    }
}
